import React, { useRef, useEffect } from 'react';
import { Student, stageOptions, academyOptions, Dormitory, Class, marketingDepartments } from '../../../shared/models';
import './StudentTable.css';

interface StudentTableProps {
  students: Student[];
  onEdit: (student: Student) => void;
  onDelete: (student: Student) => void;
  onViewDetail: (student: Student) => void;
  selectedIds: Set<string>;
  onSelectChange: (id: string, isSelected: boolean) => void;
  onSelectAll: (isSelected: boolean) => void;
  dormitories: Dormitory[];
  classes: Class[];
}

const StudentTable: React.FC<StudentTableProps> = ({ students, onEdit, onDelete, onViewDetail, selectedIds, onSelectChange, onSelectAll, dormitories, classes }) => {
  // 市场部直接使用models.ts中的定义
  
  // 根据学生状态获取对应的样式类名和文本
  const getStatusInfo = (status: string) => {
    switch (status) {
      case 'active':
        return { className: 'status-active', text: '在读' };
      case 'suspended':
        return { className: 'status-suspended', text: '休学' };
      case 'graduated':
        return { className: 'status-graduated', text: '毕业' };
      case 'transferred':
        return { className: 'status-transferred', text: '转学' };
      default:
        return { className: 'status-unknown', text: '未知' };
    }
  };

  // 获取班级名称
  const getClassName = (classId: string) => {
    const classInfo = classes.find(c => String(c.id) === String(classId));
    
    if (classInfo) {
      return classInfo.name;
    }
    
    return `班级信息未设置`;
  };

  // 获取宿舍完整信息
  const getFullDormitoryInfo = (dormitoryId: string) => {
    const dormitoryInfo = dormitories.find(d => d.id === dormitoryId);
    if (dormitoryInfo) {
      // 格式为：楼栋-房间号
      return `${dormitoryInfo.building}-${dormitoryInfo.roomNumber}`;
    }
    return '-';
  };

  // 计算是否全选
  const isAllSelected = students.length > 0 && students.every(student => selectedIds.has(student.id));
  const isPartialSelected = students.length > 0 && students.some(student => selectedIds.has(student.id)) && !isAllSelected;
  
  // 使用ref来设置indeterminate状态
  const selectAllCheckboxRef = useRef<HTMLInputElement>(null);
  
  useEffect(() => {
    if (selectAllCheckboxRef.current) {
      selectAllCheckboxRef.current.indeterminate = isPartialSelected;
    }
  }, [isPartialSelected]);

  if (students.length === 0) {
    return (
      <div className="empty-state">
        <h3>暂无学生数据</h3>
        <p>请尝试调整筛选条件或添加新学生</p>
      </div>
    );
  }

  return (
    <div className="table-container">
      <table className="student-table">
        <thead>
          <tr>
            <th>
              <input
                ref={selectAllCheckboxRef}
                type="checkbox"
                checked={isAllSelected}
                onChange={(e) => onSelectAll(e.target.checked)}
                className="select-all-checkbox"
              />
            </th>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>阶段</th>
            <th>学院</th>
            <th>市场部</th>
            <th>班级</th>
            <th>宿舍</th>
            <th>出生日期</th>
            <th>联系方式</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {students.map((student) => {
            const statusInfo = getStatusInfo(student.status);
            const isSelected = selectedIds.has(student.id);
            return (
              <tr key={student.id} className={`student-row ${isSelected ? 'selected' : ''}`}>
                <td>
                  <input
                    type="checkbox"
                    checked={isSelected}
                    onChange={(e) => onSelectChange(student.id, e.target.checked)}
                    className="student-checkbox"
                  />
                </td>
                <td className="student-id">{student.studentId}</td>
                <td 
                  className="student-name clickable-name" 
                  onClick={() => onViewDetail(student)}
                  title="点击查看详情"
                >
                  {student.name}
                </td>
                <td className="student-gender">
                  {student.gender === 'male' ? '男' : '女'}
                </td>
                <td className="student-stage">
                  {stageOptions.find(option => option.value === student.stage)?.label || student.stage}
                </td>
                <td className="student-academy">
                  {(() => {
                    // 根据学生的classId找到对应的班级
                    const classInfo = classes.find(c => String(c.id) === String(student.classId));
                    // 如果找到班级，显示班级的学院信息
                    if (classInfo && classInfo.academy) {
                      return academyOptions.find(option => option.value === classInfo.academy)?.label || classInfo.academy;
                    }
                    // 如果没有找到班级，回退到学生自己的学院信息
                    return academyOptions.find(option => option.value === student.academy)?.label || student.academy || '-';
                  })()}
                </td>
                <td className="student-marketing">
                  {student.academy && marketingDepartments.includes(student.academy) ? student.academy : '-'}
                </td>
                <td className="student-class">
                  {getClassName(Number(student.classId))}
                </td>
                <td className="student-dormitory">
                  {student.dormitoryId ? getFullDormitoryInfo(student.dormitoryId) : '-'}
                </td>
                <td className="student-birthdate">
                  {student.dateOfBirth ? new Date(student.dateOfBirth).toLocaleDateString('zh-CN') : '-'}
                </td>
                <td className="student-contact">{student.phoneNumber || '-'}</td>
                <td className="student-status">
                  <span className={`status-badge ${statusInfo.className}`}>
                    {statusInfo.text}
                  </span>
                </td>
                <td className="student-actions">
                  <button
                    className="btn-view"
                    onClick={() => onViewDetail(student)}
                    title="点击查看学生评语"
                  >
                    学生评语
                  </button>
                  <button
                    className="btn-edit"
                    onClick={() => onEdit(student)}
                    title="编辑"
                  >
                    编辑
                  </button>
                  <button
                    className="btn-delete"
                    onClick={() => onDelete(student)}
                    title="删除"
                  >
                    删除
                  </button>
                  
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

export default StudentTable;